package com.ling.pl.security.service;

import com.ling.pl.core.commons.support.DaoPage;
import com.ling.pl.core.commons.utils.AssertHelper;
import com.ling.pl.core.commons.utils.BatchUtils;
import com.ling.pl.core.dao.IDao;
import com.ling.pl.security.model.DefaultUser;
import com.ling.pl.security.model.UserOrg;
import com.ling.pl.security.model.UserPosition;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
 * @author bo.wang
 */
@Component(DefaultUserService.BEAN_ID)
public class DefaultUserService extends BaseDefaultUserService {
    @Resource
    private PasswordEncoder passwordEncoder;

    public DefaultUser loadUserByUsername(String username) {
        AssertHelper.notEmpty_assert(username, "用户名不能为空");
        DefaultUser user = defaultUserDao.loadUserByUsername(username);
//        if (user == null) {
//            String erroString = "用户名 " + username + "不存在";
//            CookieUtils.addCookie(ContextHolder.getRequest(), ContextHolder.getResponse(), LoginConstantDef.LOGIN_ERROKEY, erroString);
//            throw new UsernameNotFoundException(erroString);
//        } else {
//            if (!user.isEnabled()) {
//                throw new UsernameNotFoundException("用户已禁用");
//            }
//            return user;
//        }
        return user;
    }

    public DaoPage loadPageUsers(Map params, int pageIndex, int pageSize) {
        return defaultUserDao.loadPageUsers(params, pageIndex, pageSize);
    }

    public Collection<DefaultUser> loadUsers(Map params) {
        return defaultUserDao.loadUsers(params);
    }

    public Collection<DefaultUser> loadUsersByOrgId(String orgId) {
        return defaultUserDao.loadUsersByOrgId(orgId);
    }

    public void changePassword(String username, String newPassword) {
        DefaultUser user = (DefaultUser) loadUserByUsername(username);
        int salt = RandomUtils.nextInt(1000);
        user.setPassword(passwordEncoder.encode(newPassword));
        user.setSalt(String.valueOf(salt));
        defaultUserDao.update(user);
    }

    public String checkPassword(String username, String password) {
        DefaultUser user = (DefaultUser) loadUserByUsername(username);
        String salt = user.getSalt();
        if (!passwordEncoder.matches(user.getPassword(), password)) {
            return "密码不正确";
        } else {
            return null;
        }
    }

    public DefaultUser newUserInstance(String username) {
        return new DefaultUser(username);
    }

    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }


    public void registerAdministrator(String username, String cname,
                                      String ename, String password, String email, String mobile, String companyId) {
        int salt = RandomUtils.nextInt(1000);
        password = passwordEncoder.encode(password);
        DefaultUser user = new DefaultUser();
        user.setUsername(username);
        user.setCname(cname);
        user.setEname(ename);
        user.setPassword(password);
        user.setEmail(email);
        user.setMobile(mobile);
        user.setCompanyId(companyId);
        user.setPassword(password);
        user.setSalt(String.valueOf(salt));
        user.setAdministrator(true);
        defaultUserDao.save(user);
    }

    public void registerCommonUser(String username, String password, String cname,
                                   String ename, String email, String mobile, String companyId) {
        int salt = RandomUtils.nextInt(1000);
        password = passwordEncoder.encode(password);
        DefaultUser user = new DefaultUser();
        user.setUsername(username);
        user.setCname(cname);
        user.setEname(ename);
        user.setPassword(password);
        user.setEmail(email);
        user.setMobile(mobile);
        user.setCompanyId(companyId);
        user.setPassword(password);
        user.setSalt(String.valueOf(salt));
        defaultUserDao.save(user);
    }

    public void registerCommonUser(DefaultUser user) {
        AssertHelper.notEmpty_assert(user, "注册信息错误,空数据");
        AssertHelper.notEmpty_assert(user.getUsername(), "用户名不能为空");
        int salt = RandomUtils.nextInt(1000);
        String decodepwd = user.getPassword() == null ? "111111" : user.getPassword();
        String password = passwordEncoder.encode(decodepwd);
        user.setPassword(password);
        user.setSalt(String.valueOf(salt));
        user.setCompanyId("ling2");
        defaultUserDao.save(user);
    }


    public IDao getDao() {
        return defaultUserDao;
    }


    public void saveUsers(Map dataListsMap) {
        Collection<DefaultUser> deleteList = BatchUtils.to(DefaultUser.class).getDeleteEntities(dataListsMap);
        Collection<DefaultUser> insertList = BatchUtils.to(DefaultUser.class).getInsertEntities(dataListsMap);
        Collection<DefaultUser> updateList = BatchUtils.to(DefaultUser.class).getModifiedEntities(dataListsMap);
        if ((updateList != null) && (updateList.size() > 0)) {
            defaultUserDao.updateAll(updateList);
        }
        if ((insertList != null) && (insertList.size() > 0)) {
            for (DefaultUser user : insertList) {
                String salt = String.valueOf(RandomUtils.nextInt(100));
                String password = passwordEncoder.encode(
                        user.getPassword());
                user.setPassword(password);
                user.setSalt(salt);
//                user.setCompanyId(getFixedCompanyId());
                defaultUserDao.save(user);
            }
        }
        if ((deleteList != null) && (deleteList.size() > 0)) {
            for (DefaultUser user : deleteList) {
                defaultUserDao.remove(user);
            }
        }
    }


    public String userIsExists(String username) {
        return defaultUserDao.userIsExists(username);
    }

    public void insertUserPosition(String username, String ids) {
        Map params = new HashMap();
        params.put("username", username);
        defaultUserDao.executeHqlProduce(
                "delete from " + UserPosition.class.getName()
                        + " u where u.username = :username", params);

        if (StringUtils.isNotEmpty(ids)) {
            UserPosition userPosition;
            for (String id : ids.split(",")) {
                userPosition = new UserPosition();
                userPosition.setId(UUID.randomUUID().toString());
                userPosition.setPositionId(id);
                userPosition.setUsername(username);
                defaultUserDao.save(userPosition);
            }
        }
    }

    public void insertUserOrg(String username, String ids) {
        Map params = new HashMap();
        params.put("username", username);
        defaultUserDao.executeHqlProduce(
                "delete " + UserOrg.class.getName()
                        + " u where u.username = :username", params);

        if (StringUtils.isNotEmpty(ids)) {
            UserOrg userOrg;
            for (String id : ids.split(",")) {
                userOrg = new UserOrg();
                userOrg.setId(UUID.randomUUID().toString());
                userOrg.setOrgId(id);
                userOrg.setUsername(username);
                defaultUserDao.save(userOrg);
            }
        }
    }


    public DefaultUser getByUserName(String username) {
        AssertHelper.notEmpty_assert(username, "用户名不能为空");
        DefaultUser user = defaultUserDao.loadUserByUsername(username);
        return user;
    }

    public DefaultUser loadUserByMobile(String mobile) {
        AssertHelper.notEmpty_assert(mobile, "手机号码不能为空");
        DefaultUser user = defaultUserDao.loadUserByMobile(mobile);
        return user;
    }

    public DefaultUser loadUserByEmail(String email) {
        AssertHelper.notEmpty_assert(email, "邮箱地址不能为空");
        DefaultUser user = defaultUserDao.loadUserByEmail(email);
        return user;
    }
}

